package com.stockz.ui.swing.watchlist.widget;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import com.stockz.core.model.Bar;
import com.stockz.core.util.Global;
import com.stockz.core.util.SpringUtil;
import com.stockz.ui.swing.charting.util.UIChartingConstant;
import com.stockz.ui.swing.charting.view.StockChartPanel;
import com.stockz.ui.swing.widget.JMenuItem;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;
import com.stockz.watchlist.model.WatchListEntry;

public class AddToWatchListActionListener implements ActionListener {

	private final WatchListManager watchListManager;
	private final AddToWatchListMenu menu;
	
	public AddToWatchListActionListener(AddToWatchListMenu menu) {
		this.menu = menu;
		watchListManager = SpringUtil.getApplicationContext().getBean(WatchListManager.class);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		JMenuItem item = (JMenuItem)e.getSource();
		WatchList watchList = (WatchList)item.getPayload();
		
		WatchListEntry entry = new WatchListEntry();
		entry.setWatchList(watchList);
		StockChartPanel panel  = (StockChartPanel)Global.get(UIChartingConstant.SelectedStockChartPanel);
		entry.setScrip(panel.getStockChartPanelState().getScrip());
		List<Bar> barList = panel.getStockChartPanelState().getBarList();
		int index = menu.getStockChartRightClickPopupMenu().getPoint().getIndex();
		if(index < 0){
			index = 0;
		}
		if(barList != null && index < barList.size()){
			if(index < 0) index = 0;
			entry.setInspectionDate(barList.get(index).getDate());
			entry.setWatchList(watchList);
			watchListManager.create(entry);
			System.out.println("WatchListId :"+entry.getWatchList().getId()+"Scrip : "+entry.getScrip().getName());
		}
	}

}
